﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace HogoLogic
{
	[Serializable]
	public class HogoProjectList
	{
		static private readonly BinaryFormatter formatter = new BinaryFormatter();

		private Collection<HogoProject> projects = new Collection<HogoProject>();
		
		public int ProjectCount
		{
			get
			{
				return projects.Count;
			}
		}

		public IEnumerator<HogoProject> GetEnumerator()
		{
			return projects.GetEnumerator();
		}
		
		/// <summary>
		/// 
		/// </summary>
		/// <param name="newProject"></param>
		/// <returns>is succesfully</returns>
		public bool Add(HogoProject newProject)
		{
			foreach (HogoProject potentialySameProject in projects)
			{
				if (potentialySameProject.Name == newProject.Name ||
					potentialySameProject.WorkingDir == newProject.WorkingDir)
					return false;
			}
			
			projects.Add(newProject);
			return true;
		}

		#region Singletone
		private HogoProjectList()
		{}

		static private HogoProjectList instance = new HogoProjectList();

		static public HogoProjectList Instance
		{
			get
			{
				return instance;
			}
		}
		#endregion

		#region Save/Load
		static public void SaveToFile(string fileName)
		{
			Stream stream = File.Open(fileName, FileMode.Create);
			formatter.Serialize(stream, instance);
			stream.Close();
		}

		static public void LoadFromFile(string fileName)
		{
			Stream stream = null;
			try
			{
				stream = File.Open(fileName, FileMode.Open);
				instance = (HogoProjectList)formatter.Deserialize(stream);
			}
			catch
			{
				instance = new HogoProjectList();
			}
			finally
			{
				if (stream != null)
					stream.Close();
			}
		}
		#endregion
	}
}
